package com.feihong.txgw.ui.activity.user;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.feihong.txgw.R;
import com.feihong.txgw.adapter.delivery.DeliveryAdrAdapter;
import com.feihong.txgw.inter.contract.adr.IDeliveryAdrContract;
import com.feihong.txgw.inter.listener.delivery_adr.DeliveryAdrDeleteAdrListener;
import com.feihong.txgw.inter.listener.delivery_adr.DeliveryAdrEditListener;
import com.feihong.txgw.message.DeliveryAdrChangeMessage;
import com.feihong.txgw.message.LoginMessage;
import com.feihong.txgw.model.base_bean.BaseResponse;
import com.feihong.txgw.model.bean.deliveryAdr.DeliveryAdrEntity;
import com.feihong.txgw.tx_precenter.DeliveryAdrMainPrecenter;
import com.feihong.txgw.ui.mvp.BaseMVPCompateActivity;
import com.feihong.txgw.ui.mvp.precenter.AbBasePrecenter;
import com.feihong.txgw.utils.PreferenceTools;
import com.feihong.txgw.utils.kaika.KaikaIntentType;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * @author wangziheng
 * @name txgw_app
 * @class name：com.feihong.txgw.ui.activity.user
 * @class describe: 收货地址
 * @time 2017/7/4 13:56
 * @change
 * @chang time
 * @class describe
 */
public class MyDeliveryAdrActivity extends BaseMVPCompateActivity<IDeliveryAdrContract.AbDeliveryAdrMainPrecenter> implements View.OnClickListener, DeliveryAdrDeleteAdrListener, DeliveryAdrEditListener,IDeliveryAdrContract.IDeliveryAdrMainView {

    /**
     * 标题栏
     */
    @BindView(R.id.btn_back) ImageView mEditBtn;
    @BindView(R.id.txt_pagetitle) TextView mAdrTitle;
    @BindView(R.id.top_back_layout) RelativeLayout mTopLayout;
    @BindView(R.id.MyDeliveryAdrRecyclerView) RecyclerView mDeliveryAdrRecyclerView;
    private LinearLayoutManager mLinearLayouManager;
    private DeliveryAdrAdapter mDeliverAdrAdapter;
    private ArrayList<DeliveryAdrEntity> mDeliveryAdrEntityList;
    /**
     * 添加地址
     */
    private static final int ADDADRESS = 1;


    @BindView(R.id.delivery_adr_add_newAdr) LinearLayout mAddAdrLayout;

    /**
     * 展示收货地址layout
     */
    @BindView(R.id.delivery_show_layout) RelativeLayout mAdrShowLayout;
    /**
     * 暂无收货地址layout
     */
    @BindView(R.id.delivery_adr_no_layout) LinearLayout mAdrNoLayout;
    @BindView(R.id.delivery_adr_to_add_adr) LinearLayout mAdrNullAddAdrLayout;

    /**
     * 加载动画layout
     */
    @BindView(R.id.lay_loading) RelativeLayout mLoadLayout;

    private Intent mCreateOrderIntent;

    @BindView(R.id.connect_net_error_layout) LinearLayout mConnectEorrLayout;
    @BindView(R.id.re_query_data_layout) LinearLayout mReQueryDataLayout;
    public static final int ADR_ITEMCLICK_REQUEST_CODE = 10;

    public final static String SELECT_ADR_KEY = "SELECT_DELIVERY_ADR";
    public final static String DEFAULT_ADR_KEY = "DEFAULT_ADR_KEY";

    private DeliveryAdrEntity mAlSelectAdr;

    @Override
    public void setTheme() {

    }

    @Override
    public int setLayoutID() {
        return R.layout.activity_delivery_adr_layout;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        EventBus.getDefault().register(this);
        mAlSelectAdr = new DeliveryAdrEntity();
        if(!TextUtils.isEmpty(PreferenceTools.getString(SELECT_ADR_KEY,""))){
            mAlSelectAdr = JSON.parseObject(PreferenceTools.getString(MyDeliveryAdrActivity.SELECT_ADR_KEY, null), DeliveryAdrEntity.class);
        }
        mConnectEorrLayout.setVisibility(View.GONE);
        mTopLayout.setBackgroundColor(getResources().getColor(R.color.bg_white));
        mAdrTitle.setTextColor(getResources().getColor(R.color.black_text));
        mDeliveryAdrEntityList = new ArrayList<>();
        mLinearLayouManager = new LinearLayoutManager(this);
        mDeliveryAdrRecyclerView.setLayoutManager(mLinearLayouManager);
        mDeliverAdrAdapter = new DeliveryAdrAdapter(this);
        mDeliveryAdrRecyclerView.setAdapter(mDeliverAdrAdapter);

        mAdrShowLayout.setVisibility(View.GONE);
        mAdrNoLayout.setVisibility(View.GONE);

    }

    @Override
    public void bindData() {

        mEditBtn.setOnClickListener(this);
        mAddAdrLayout.setOnClickListener(this);
        mAdrNullAddAdrLayout.setOnClickListener(this);
        mDeliverAdrAdapter.setDeliveryAdrDeleteListener(this);
        mDeliverAdrAdapter.setDeliveryAdrEditListener(this);
        mReQueryDataLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mReQueryDataLayout.setVisibility(View.VISIBLE);
                mConnectEorrLayout.setVisibility(View.GONE);
                mLoadLayout.setVisibility(View.VISIBLE);
                getAdrData();
            }
        });
        mCreateOrderIntent = getIntent();
        if (!TextUtils.isEmpty(mCreateOrderIntent.getStringExtra(KaikaIntentType.ADRESS_INTENT_TYPE_KEY)) && KaikaIntentType.ADDRESS_INTENT_TYPE_ITEN_CLICK_BACK.equals(mCreateOrderIntent.getStringExtra(KaikaIntentType.ADRESS_INTENT_TYPE_KEY))) {
            mDeliverAdrAdapter.setSelectOrderAdr(KaikaIntentType.ADDRESS_INTENT_TYPE_ITEN_CLICK_BACK);
            mAdrTitle.setText("请选择收货地址");
        } else if (!TextUtils.isEmpty(mCreateOrderIntent.getStringExtra(KaikaIntentType.ADRESS_INTENT_TYPE_KEY)) && KaikaIntentType.ADDRESS_INTENT_TYPE_ITEM_CLICK_NEXT_PACKAGE.equals(mCreateOrderIntent.getStringExtra(KaikaIntentType.ADRESS_INTENT_TYPE_KEY))) {
            mDeliverAdrAdapter.setSelectOrderAdr(KaikaIntentType.ADDRESS_INTENT_TYPE_ITEM_CLICK_NEXT_PACKAGE);
            mAdrTitle.setText("请选择收货地址");
        } else {
            mDeliverAdrAdapter.setSelectOrderAdr(KaikaIntentType.ADRESS_INTENT_TYPE_NORMAL);
            mAdrTitle.setText(getResources().getString(R.string.delivery_adr_title_tv));
        }
        mLoadLayout.setVisibility(View.VISIBLE);
        getAdrData();
    }

    /**
     * 获取收货地址信息
     */

    private void getAdrData() {
        mDeliveryAdrEntityList.clear();

        if (mAdrNoLayout != null) {
            mAdrNoLayout.setVisibility(View.GONE);
        }
        mPresenter.getDeliveryAdrInfo();
    }

    @Override
    public void onUserLogin(LoginMessage loginMessage) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                if (mLoadLayout != null && mLoadLayout.getVisibility() == View.VISIBLE) {
                    return;
                }
                finish();
                break;
            case R.id.delivery_adr_add_newAdr:
                Intent intent = new Intent(this, MyDeliveryAdrEditActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("type", "0");
                intent.putExtras(bundle);
                startActivityForResult(intent, ADDADRESS);
                getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                break;
            case R.id.delivery_adr_to_add_adr:
                Intent intent_no = new Intent(this, MyDeliveryAdrEditActivity.class);
                Bundle bundle_no = new Bundle();
                bundle_no.putString("type", "0");
                intent_no.putExtras(bundle_no);
                startActivityForResult(intent_no, ADDADRESS);
                getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
                break;
            default:
                break;
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 删除地址
     *
     * @param position
     */
    private boolean isChangeAdr = false;

    @Override
    public void onDeleteAdr(final DeliveryAdrEntity entity) {
        showConfirmDialog(null, "确定要删除该地址吗？", "删除", "取消", new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(final SweetAlertDialog sweetAlertDialog) {
                // 判断删除的是否是默认地址
                sweetAlertDialog.dismiss();
                mLoadLayout.setVisibility(View.VISIBLE);
                if (mAlSelectAdr != null && !TextUtils.isEmpty(mAlSelectAdr.getAddr_id())) {
                    if (mAlSelectAdr.getAddr_id().equals(entity.getAddr_id())) {
                        isChangeAdr = true;
                    } else {
                        isChangeAdr = false;
                    }
                } else {
                    isChangeAdr = true;
                }
                mPresenter.delDeliveryAdr(entity.getAddr_id());
            }
        }, new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                mLoadLayout.setVisibility(View.GONE);
                sweetAlertDialog.dismiss();
            }
        });
    }

    /**
     * 编辑地址
     * @param entity
     */
    @Override
    public void onEditAdr(DeliveryAdrEntity entity) {
        Intent intent = new Intent(this, MyDeliveryAdrEditActivity.class);
        Bundle bundle = new Bundle();
        bundle.putParcelable("adressInfo", entity);
        bundle.putString("type", "1");
        intent.putExtras(bundle);
        startActivity(intent);
    }

    @Override
    public void onBackPressedSupport() {
        if (mLoadLayout != null && mLoadLayout.getVisibility() == View.VISIBLE) {
            mLoadLayout.setVisibility(View.GONE);
            return;
        }
        super.onBackPressedSupport();
    }

    /**
     * 编辑收货地址后刷新数据
     * @param deliveryAdrChangeMessage
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshDeliveryAdr(DeliveryAdrChangeMessage deliveryAdrChangeMessage) {
        mLoadLayout.setVisibility(View.VISIBLE);
        getAdrData();
    }

    @Override
    public void getDeliveryAdrInfoError() {
        mLoadLayout.setVisibility(View.GONE);
        if (mDeliveryAdrEntityList.size() == 0) {
            mConnectEorrLayout.setVisibility(View.VISIBLE);
            mAdrNoLayout.setVisibility(View.GONE);
            mAdrShowLayout.setVisibility(View.GONE);
        } else {
            mConnectEorrLayout.setVisibility(View.GONE);
            mAdrNoLayout.setVisibility(View.GONE);
            mAdrShowLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void delDeliveryAdrError() {
        showDialog(null, getResources().getString(R.string.connect_service_error));
        mLoadLayout.setVisibility(View.GONE);
    }

    @Override
    public void getDeliveryAdrInfoResult(String result) {
        mLoadLayout.setVisibility(View.GONE);
        try {
            JSONObject jsonObject = new JSONObject(result);
            if ("200".equals(jsonObject.optString("code"))) {
                mAdrShowLayout.setVisibility(View.VISIBLE);
                mAdrNoLayout.setVisibility(View.GONE);
                mConnectEorrLayout.setVisibility(View.GONE);
                JSONArray jsonArray = jsonObject.optJSONArray("data");
                if (jsonArray != null) {
                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject deliveryAdrEntity = jsonArray.getJSONObject(i);
                        DeliveryAdrEntity deliveryAdr = JSON.parseObject(deliveryAdrEntity.toString(), DeliveryAdrEntity.class);
                        mDeliveryAdrEntityList.add(deliveryAdr);
                    }
                }
                boolean isHasDefaultAdr = false;
                for (DeliveryAdrEntity deliveryAdrEntity : mDeliveryAdrEntityList) {
                    if ("1".equals(deliveryAdrEntity.getIs_default())) {
                        String defaultAdrStr = JSON.toJSONString(deliveryAdrEntity);
                        PreferenceTools.putString(DEFAULT_ADR_KEY,defaultAdrStr );
                        if(isChangeAdr){
                            PreferenceTools.putString(SELECT_ADR_KEY,defaultAdrStr);
                        }
                        isHasDefaultAdr = true;
                        break;
                    }
                }
                if (!isHasDefaultAdr && mDeliveryAdrEntityList.size() > 0) {
                    PreferenceTools.putString(DEFAULT_ADR_KEY, JSON.toJSONString(mDeliveryAdrEntityList.get(0)));
                }
                mDeliverAdrAdapter.setAdrList(mDeliveryAdrEntityList);
            } else if ("5007".equals(jsonObject.optString("code"))) {
                mAdrShowLayout.setVisibility(View.GONE);
                mAdrNoLayout.setVisibility(View.VISIBLE);
                mConnectEorrLayout.setVisibility(View.GONE);
                PreferenceTools.putString(DEFAULT_ADR_KEY, "");
            } else {
                mAdrShowLayout.setVisibility(View.GONE);
                mAdrNoLayout.setVisibility(View.VISIBLE);
                mConnectEorrLayout.setVisibility(View.GONE);
                showSystemToast(jsonObject.optString("msg"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void delDeliveryAdrResult(BaseResponse result) {
        mLoadLayout.setVisibility(View.GONE);
        if(200 == result.code){
            if(isChangeAdr){
                PreferenceTools.putString(SELECT_ADR_KEY,"");
            }
            getAdrData();
        }else {
            showDialog(null, "删除地址失败，请重新操作");
        }
    }

    @Override
    public void loadDataComplated() {

    }

    @Override
    public void loadDataError() {

    }

    @NonNull
    @Override
    public AbBasePrecenter initPresenter() {
        return DeliveryAdrMainPrecenter.create();
    }
}
